package com.xingtu.testSerialport.receiver;


import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import com.blankj.utilcode.util.LogUtils;
import com.xingtu.testSerialport.MyApplication;
import com.xingtu.testSerialport.eventbus.NetWorkEvent;

import org.greenrobot.eventbus.EventBus;


/**
 * 这个receiver在BaseApplication里注册
 * 判断网络是否链接，更新view
 * 如果断网则显示设置网络
 * */
public class NetworkStateReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

        int isWifi = 0;

        if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {//监听网络连接
            //获取联网状态的NetworkInfo对象
            NetworkInfo info = intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
            if (info != null) {
                //如果当前的网络连接成功并且网络连接可用
                if (NetworkInfo.State.CONNECTED == info.getState() && info.isAvailable()) {
                    if (info.getType() == ConnectivityManager.TYPE_WIFI){
                        LogUtils.e("连接上WiFi");
                        isWifi = 1;
                    }else if (info.getType() == ConnectivityManager.TYPE_MOBILE){
                        LogUtils.e("连接上移动网络数据");
                        isWifi = 0;
                    }
                } else {
                    LogUtils.e("网络断开");
                    isWifi = -1;
                }
                MyApplication.myPreferences.setIsWifi(isWifi);
            }
        }
        EventBus.getDefault().post(new NetWorkEvent(isWifi));
    }

}